<template>
  <div id="guide-map" style="width: 100%; height: 100%">
    <div style="display: flex; justify-content: center">
      <el-select
        v-model="targetAddress"
        placeholder="搜索地址"
        style="width: 60%; z-index: 1; margin-top: 10px"
        size="small"
        filterable
        remote
        value-key="id"
        :remote-method="getSearch"
        :loading="loading"
        @change="currentSelect"
      >
        <el-option v-for="item in addressOptions" :key="item.id" :label="item.name" :value="item">
          <span style="float: left">{{ item.name }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px; margin-left: 10px">
            {{ item.address }}
          </span>
        </el-option>
      </el-select>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import type { Ref } from 'vue';
import GdMapUtil from '@/utils/gdMapUtil';
import type { Map, Marker } from '@amap/amap-jsapi-loader';

interface AddressOption {
  id: string;
  name: string;
  address: string;
  location: {
    lng: number;
    lat: number;
  };
}

const loading = ref(true);
const mapCenter: Ref<[number, number]> = ref([0, 0]);
const map: Ref<Map | null> = ref(null);
const marker: Ref<Marker | null> = ref(null);
const targetAddress = ref<AddressOption>();
const addressOptions = ref<AddressOption[]>([]);

const getMap = async () => {
  const AMap = await GdMapUtil.initAMap();
  map.value = new AMap.Map('guide-map', {
    viewMode: '2D',
    zoom: 11,
    center: mapCenter.value,
  });
};

const setMark = async (lng: number, lat: number) => {
  if (isNaN(lng) || isNaN(lat)) {
    console.error('Invalid coordinates:', lng, lat);
    return;
  }

  if (marker.value && map.value) {
    map.value.remove(marker.value);
  }

  try {
    const newMarker = await GdMapUtil.setMarker(lng, lat);
    marker.value = newMarker;
    if (map.value) {
      map.value.add(newMarker);
    }
  } catch (error) {
    console.error('Failed to set marker:', error);
  }
};

const getSearch = async (query: string) => {
  addressOptions.value = [];
  if (query === '') return;
  try {
    const res = await GdMapUtil.getPlaceSearch(query);
    loading.value = false;
    addressOptions.value = res.poiList.pois;
  } catch (error) {
    console.error('Search failed:', error);
  }
};

const currentSelect = (val: AddressOption | null) => {
  if (!val || !map.value) return;
  targetAddress.value = val;
  map.value.setFitView();
  setMark(val.location.lng, val.location.lat);
  map.value.setCenter([val.location.lng, val.location.lat]);
  emit('close-drawer', val);
};

const emit = defineEmits<{
  (event: 'close-drawer', value: AddressOption): void;
}>();

onMounted(async () => {
  try {
    const res = await GdMapUtil.getLocationCity();
    mapCenter.value = [res.position.getLng(), res.position.getLat()];
    await getMap();
    await setMark(res.position.getLng(), res.position.getLat());
  } catch (error) {
    console.error('Failed to get location:', error);

    // 尝试加载地图而不依赖于地理位置
    await getMap();
    // 设置默认中心点或其他逻辑
    mapCenter.value = [116.397428, 39.90923]; // 北京市经纬度作为示例
  }
});
onUnmounted(() => {
  GdMapUtil.destroyMap();
});
</script>

<style scoped lang="less">
#guide-map {
  width: 100%;
  height: 100%;
}
</style>
